package codemaster.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public abstract class Styler
{
	/**
	 * Cleans a file, including the following: 1) Remove the trailing spaces or
	 * tab at the end of a line. 2) Replace any 4 spaces with a tab at the
	 * beginning of the line and discard any remaining spaces. The input file
	 * will be overwritten.
	 * 
	 * @param inputFile the input file
	 */
	public static void clean(File inputFile)
	{
		BufferedWriter bfw = null;
		BufferedReader bfr = null;
		StringBuffer sbLine;
		StringBuffer sbSpace;
		StringBuffer sbFile = new StringBuffer(4000);
		boolean isPadding;
		try
		{
			// Reads the table columns
			bfr = new BufferedReader(new FileReader(inputFile));
			String line = bfr.readLine();
			while (line != null)
			{
				isPadding = true;
				// Skips comment lines
				if (line.startsWith(" *") || line.startsWith("\t* "))
				{
					sbFile.append(line + "\n");
					line = bfr.readLine();
					continue;
				}
				sbLine = new StringBuffer(80);
				sbSpace = new StringBuffer(12);
				for (int i = 0; i < line.length(); i++)
				{
					if (isPadding)
					{
						if (line.charAt(i) == '\t')
						{
							sbLine.append(line.charAt(i));
						}
						else if (line.charAt(i) == ' ')
						{
							sbSpace.append(line.charAt(i));
						}
						else
						{
							sbLine.append(replace(sbSpace));
							sbLine.append(line.charAt(i));
							isPadding = false;
						}
					}
					else
					{
						sbLine.append(line.charAt(i));
					}
				}

				for (int i = sbLine.length() - 1; i >= 0; i--)
				{
					if (sbLine.charAt(i) == '\t' || sbLine.charAt(i) == ' ')
					{
						sbLine.deleteCharAt(i);
					}
					else
					{
						break;
					}
				}
				sbFile.append(sbLine + "\n");

				line = bfr.readLine();
			}
			bfr.close();

			bfw = new BufferedWriter(new FileWriter(inputFile));

			bfw.write(sbFile.toString());
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (bfw != null)
			{
				try
				{
					bfw.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

	}

	private static String replace(StringBuffer sbBlank)
	{
		String result = "";
		for (int i = 0; i < sbBlank.length()-2; i += 4)
		{
			result += "\t";
		}
		return result;
	}
}